import io
import subprocess

from PIL import Image


def adb_shell(command):
    full_command = ['adb', 'shell'] + command
    result = subprocess.run(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        print("Error:", result.stderr.decode('utf-8'))
        raise Exception(f"ADB command failed with error: {result.stderr.decode('utf-8')}")
    return result.stdout

# 获取屏幕截图的二进制数据
screenshot_data = adb_shell(['screencap', '-p'])

# 打印前几个字节以检查数据格式
print(screenshot_data[:10])

# 将二进制数据写入临时文件以便手动检查
with open('temp_screenshot.bin', 'wb') as f:
    f.write(screenshot_data)

# 尝试打开图像文件
try:
    image = Image.open(io.BytesIO(screenshot_data))
    image.show()
    image.save('1.png')
except Exception as e:
    print("Failed to open image:", e)
